package it.mauriziobasile.andoid.aub.utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.telephony.SmsMessage;

public class Tools {
    public static String httpDateFormat = "EEE, dd MMM yyyy HH:mm:ss 'GMT'";

    public static SmsMessage[] getMessagesFromIntent(Intent intent) {
        SmsMessage retMsgs[] = null;
        Bundle bdl = intent.getExtras();
        try {
            Object pdus[] = (Object[]) bdl.get("pdus");
            retMsgs = new SmsMessage[pdus.length];
            for (int n = 0; n < pdus.length; n++) {
                byte[] byteData = (byte[]) pdus[n];
                retMsgs[n] = SmsMessage.createFromPdu(byteData);
            }
        } catch (Exception e) {
            Logger.e("fail " + e.getMessage());
        }
        return retMsgs;
    }

    public static String capitalize(String input) {
        String val = new String();
        String[] words = input.trim().split("\\s");
        for (String string : words) {
            if (string.trim().length() > 1) {
                val += string.trim().substring(0, 1).toUpperCase();
                val += string.trim().substring(1).toLowerCase();
            } else {
                val += string.trim().toUpperCase();
            }
            val += " ";
        }
        return val;
    }

    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public static String formattaDataUltimoRefresh(Date date) {
        SimpleDateFormat formatter = new SimpleDateFormat("d MMM HH:mm");
        return formatter.format(date);
    }

    public static String formatDateForHttpRequest(Date ifModSince) {
        SimpleDateFormat format = new SimpleDateFormat(httpDateFormat, Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        return format.format(ifModSince);
    }

}
